/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.pay.interceptor.manager.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pub.pjoc.pay.interceptor.InterceptResult;
import pub.pjoc.pay.interceptor.PayInterceptor;
import pub.pjoc.pay.interceptor.manager.InterceptorManager;
import pub.pjoc.pay.vo.PayRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Default implement.
 *
 * @author blademainer
 * @version 2016-09-07 22:49
 */
public class InterceptorManagerImpl implements InterceptorManager {
  private static final Logger logger = LoggerFactory.getLogger(InterceptorManagerImpl.class);
  private List<PayInterceptor> interceptors = new ArrayList<>();
  private AtomicBoolean writing = new AtomicBoolean();

  @Override
  public InterceptResult intercept(PayRequest request) {
    checkLock();
    for (PayInterceptor interceptor : interceptors) {
      InterceptResult interceptResult = interceptor.intercept(request);
      if (!interceptResult.isSuccess()) {
        logger.info("Intercepted a pay request. request: {}, result: {}", request, interceptResult);
        interceptResult.setInterceptor(interceptor);
        return interceptResult;
      }
      if (logger.isDebugEnabled()) {
        logger.debug("Passed a pay request. request: {}, result: {}", request, interceptResult);
      }
    }
    return InterceptResult.SUCCESS;
  }

  private void checkLock() {
    while (writing.get()) {
      logger.debug("Try to intercept, but interceptor is modify, so wait for done.");
    }
  }

  public void addInterceptor(PayInterceptor interceptor) {
    while (!writing.compareAndSet(false, true)) {
      logger.warn("Try to write, but another is locking, so wait for another thread done...");
    }
    interceptors.add(interceptor);
    if (logger.isDebugEnabled()) {
      logger.debug("Added interceptor: {}", interceptor);
    }
    sortInterceptors();
    if (logger.isDebugEnabled()) {
      logger.debug("Added interceptor: {} sorted interceptors: {}", interceptor, interceptors);
    }
    while (!writing.compareAndSet(true, false)) {
      logger.warn("Try to unlock, but another is locking, so wait for another thread done...");
    }
  }

  private void sortInterceptors() {
    Collections.sort(interceptors, (o1, o2) -> {
      if (o1 == null) {
        return 1;
      }
      if (o2 == null) {
        return -1;
      }
      if (o1.priority() <= o2.priority()) {
        return -1;
      } else if (o1.priority() >= o2.priority()) {
        return 1;
      }
      return 0;
    });
  }

  public List<PayInterceptor> getInterceptors() {
    return interceptors;
  }

  public void setInterceptors(List<PayInterceptor> interceptors) {
    interceptors.forEach(this::addInterceptor);
  }
}
